<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var connect = function (root) {
        function levelOrder(root) {
          if (!root) return root
          let queue = [root]
          let pre = null
          while (queue.length) {
            let len = queue.length
            let pre = null
            for (let i = 0; i < len; i++) {
              let node = queue.shift()
              if (i == 0) {
                pre = node
              } else {
                pre.next = node
                pre = node
              }
              if (node.left) {
                queue.push(node.left)
              }
              if (node.right) {
                queue.push(node.right)
              }
            }
            pre.next = null
          }
          return root
        }
        return levelOrder(root)
      }
    </script>
  </body>
</html>
